package com.cyj.dream.core.util.http.httpclient;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @Description: 基于httpclient封装的http请求类搭配了 hutool，支持put/get/post
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.core.util.http.httpclient
 * @Author: ChenYongJia
 * @CreateTime: 2021-09-26 13:18
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
public class HttpUtils {

    /**
     * 自定义httpPost方法，使用org.apache.http.client实现
     * 问题：请求超时，无法通过VPN请求接口，需进一步调试
     *
     * @param url                      请求的地址
     * @param object
     * @param connectionTimeout        连接超时时间
     * @param connectionRequestTimeout 请求连接超时时间
     * @param socketTimeout            套接字超时时间
     * @return
     */
    public static Object httpClientPost(String url, Object object, Integer connectionTimeout, Integer connectionRequestTimeout, Integer socketTimeout) {
        log.info("请求路径==============>{}", url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 设置请求的Config
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout).build();
        httpPost.setConfig(requestConfig);

        // 设置请求的header
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");

        // 设置请求的body
        StringEntity entity = new StringEntity(JSONObject.toJSONString(object), ContentType.APPLICATION_JSON);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");

        httpPost.setEntity(entity);

        // 执行请求
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            //得到请求结果
            log.info("请求得到的结果:{}", response.getStatusLine());
            //得到请求回来的数据
            HttpEntity entityResult = response.getEntity();

            // 解析返回结果
            String result = EntityUtils.toString(entityResult, "utf-8");
            JSONObject jsonObject = JSONObject.parseObject(result);

            // 打印执行结果
            log.info("打印执行结果======>[}", jsonObject);
            return jsonObject;
        } catch (Exception ex) {
            String errTime = HttpUtils.formatTime();

            log.error(errTime + "  发送 POST 请求：" + url + "，出现异常error: " + ex);
            return null;
        }
    }

    /**
     * 返回错误时间
     *
     * @return
     */
    public static String formatTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String errTime = dateFormat.format(new Date());
        return errTime;
    }

    /**
     * 封装httpRequest Get方法
     *
     * @param url               请求的地址
     * @param paramsMap         传递的参数
     * @param connectionTimeout 连接超时时间
     * @return
     */
    public String httpRequestGet(String url, Map<String, Object> paramsMap, Integer connectionTimeout) {
        log.info("请求路径==============>{}", url);
        try {
            HttpResponse response = HttpRequest.get(url)
                    .form(paramsMap)
                    .timeout(connectionTimeout)
                    .execute();

            // 响应状态
            int status = 200;
            // 判断请求状态是否正常
            if (response.getStatus() == status) {
                String result = response.body();
                return result;
            } else {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String errTime = dateFormat.format(new Date());
                log.error(errTime + "  response error(" + response.getStatus() + "):" + url);
                return null;
            }
        } catch (Exception ex) {
            String errTime = HttpUtils.formatTime();
            log.error(errTime + "  request" + url + "error: " + ex.getMessage());
            return null;
        }
    }

    /**
     * 封装httpRequest Post方法
     *
     * @param url               请求的地址
     * @param jsonBody          json请求体
     * @param connectionTimeout 连接超时时间
     * @return
     */
    public JSONObject httpRequestPost(String url, String jsonBody, Integer connectionTimeout) {
        try {
            // 向壳牌CRM发起请求，使用cn.hutool.http.HttpRequest，返回对象为cn.hutool.http.HttpResponse
            HttpResponse response = HttpRequest.post(url)
                    .contentType("application/json")
                    .timeout(connectionTimeout)
                    .body(jsonBody)
                    .execute();

            // 判断请求状态是否正常
            return responseStatus(response, url);
        } catch (Exception ex) {
            String errTime = HttpUtils.formatTime();
            log.error(errTime + "  request" + url + "error: " + ex.getMessage());
            return null;
        }
    }

    /**
     * 封装httpRequest Put方法
     *
     * @param url               请求的地址
     * @param jsonBody          json请求体
     * @param connectionTimeout 连接超时时间
     * @return
     */
    public JSONObject httpRequestPut(String url, String jsonBody, Integer connectionTimeout) {
        try {
            // 向壳牌CRM发起请求，使用cn.hutool.http.HttpRequest，返回对象为cn.hutool.http.HttpResponse
            HttpResponse response = HttpRequest.put(url)
                    .contentType("application/json")
                    .timeout(connectionTimeout)
                    .body(jsonBody)
                    .execute();

            // 判断请求状态是否正常
            return responseStatus(response, url);
        } catch (Exception ex) {
            String errTime = HttpUtils.formatTime();
            log.error(errTime + "  request" + url + "error: " + ex.getMessage());
            return null;
        }
    }

    /**
     * 判断请求状态是否正常
     *
     * @param response 响应信息
     * @param url      请求的地址
     * @return
     */
    public JSONObject responseStatus(HttpResponse response, String url) {
        // 响应状态
        int status = 200;

        // 判断请求状态是否正常
        if (response.getStatus() == status) {
            String result = response.body();
            com.alibaba.fastjson.JSONObject jsonResult = JSON.parseObject(result);
            return jsonResult;
        } else {
            String errTime = HttpUtils.formatTime();
            log.error(errTime + "  response error(" + response.getStatus() + "):" + url);
            return null;
        }
    }

}
